package org.example.servlet;

import org.example.DAO.UserDao;
import org.example.entity.User;
import org.example.impl.UserDaoImpl;
import org.example.Util.DataSourceUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

@WebServlet("/userProfile")
@MultipartConfig
public class UserProfileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("Userlogin.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");

        try {
            // 处理普通表单字段
            String gender = getParameterValue(request, "gender");
            String email = getParameterValue(request, "email");
            String phone = getParameterValue(request, "phone");
            String birthday = getParameterValue(request, "birthday");
            String province = getParameterValue(request, "province");
            String city = getParameterValue(request, "city");

            // 验证邮箱
            if (email == null || email.trim().isEmpty()) {
                request.setAttribute("error", "电子邮箱不能为空");
                request.getRequestDispatcher("profile.jsp").forward(request, response);
                return;
            }

            if (!email.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
                request.setAttribute("error", "请输入有效的邮箱地址");
                request.getRequestDispatcher("profile.jsp").forward(request, response);
                return;
            }

            // 更新用户对象
            user.setGender(gender);
            user.setEmail(email);
            user.setPhone(phone);
            user.setBirthday(birthday);
            user.setProvince(province);
            user.setCity(city);

            // 处理头像上传
            Part filePart = request.getPart("avatar");
            if (filePart != null && filePart.getSize() > 0) {
                try (InputStream inputStream = filePart.getInputStream()) {

                }
            }

            // 更新数据库
            UserDao userDao = new UserDaoImpl(DataSourceUtil.getDataSource());
            if (userDao.updateUserInfo(user)) {
                request.setAttribute("message", "个人资料更新成功");
                session.setAttribute("user", user);
            } else {
                request.setAttribute("error", "个人资料更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            String errorMessage = "数据库错误: " + e.getMessage() +
                    ", SQL状态: " + e.getSQLState() +
                    ", 错误码: " + e.getErrorCode();
            request.setAttribute("error", errorMessage);
        }

        request.getRequestDispatcher("profile.jsp").forward(request, response);
    }

    // 辅助方法：从multipart请求中获取参数值（Java 8兼容版本）
    private String getParameterValue(HttpServletRequest request, String paramName) throws IOException, ServletException {
        Part part = request.getPart(paramName);
        if (part != null && part.getSubmittedFileName() == null) {
            try (InputStream inputStream = part.getInputStream()) {
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }
                // 使用UTF-8编码转换为字符串
                return result.toString("UTF-8");
            }
        }
        return null;
    }
}